<?php

class Backend_Model_DbTable_User extends Zend_Db_Table_Abstract
{

    protected $_name = 'user';

    public function getAll($limit = null, $sales_id = null){
        if($sales_id) $where = "sales_id = $sales_id";
        else $where = null;

        if(is_null($limit)) return $this->fetchAll($where, "full_name");
        else return $this->fetchAll ($where, "full_name", $limit[1], $limit[0]);
    }

    public function getUserById($id){
        return $this->fetchRow("user_id = $id");
    }

    public function getUserByEmail($email){
        return $this->fetchRow("email = '$email'");
    }

    public function insertUser($data){
        $new_data = array(
            'full_name' => $data['full_name'],
            'email' => $data['email'],
            'password' => sha1($data['password']),
            'ic_number' => $data['ic_number'],
            'gender' => $data['gender'],
            'phone' => $data['phone'],
            'company' => $data['company'],
            'sales_id' => $data['sales_id']
        );
        $this->insert($new_data);
    }

    public function updateUser($id, $data){
        $new_data = array(
            'full_name' => $data['full_name'],
            'email' => $data['email'],
            'ic_number' => $data['ic_number'],
            'gender' => $data['gender'],
            'phone' => $data['phone'],
            'company' => $data['company']
        );
        $this->update($new_data, "user_id = $id");
    }

    public function deleteUser($id){
        //move to user_deleted
        $user = $this->fetchRow("user_id = $id")->toArray();
        $db = $this->getAdapter();
        $db->insert("user_deleted", array(
            'user_id' => $user['user_id'],
            'full_name' => $user['full_name'],
            'email' => $user['email'],
            'password' => $user['password'],
            'ic_number' => $user['ic_number'],
            'gender' => $user['gender'],
            'phone' => $user['phone'],
            'company' => $user['company'],
            'sales_id' => $user['sales_id']
        ));

        //delete from original table
        $this->delete("user_id = $id");
    }
}